from flask import Flask, views, url_for
from werkzeug.routing import BaseConverter

app = Flask(__name__)
app.config.from_object('settings.DevelopmentConfig')

class RegexConverter(BaseConverter):
    """自定义url匹配正则表达式"""
    def __init__(self,map,regex):
        super(RegexConverter, self).__init__(map)
        self.regex = regex

    def to_python(self, value):
        """
        路由匹配成功后，传递给视图函数中参数值
        :param value:
        :return:
        """
        return int(value)

    def to_url(self, value):
        """
        使用url_for方向生成url时候，传递的参数经过该方法处理，返回的只用于
        生成URL中的参数
        :param value:
        :return:
        """
        val = super(RegexConverter,self).to_url(value)
        return val

# 添加到flask中
app.url_map.converters['regex'] = RegexConverter

@app.route('/index/<regex("\d+"):nid>')
def index(nid):
    # url_for(endpoint: str, **values: t.Any) -> str:  nid位**values
    print(url_for('index', nid=nid))  # /index/213214  外面传进来
    print(url_for('index', nid='123')) # /index/123     里面修改的
    return 'Index1234'

if __name__ == '__main__':
    app.run()














